package com.uinnova.product.eam.config;

import cn.hutool.json.JSONObject;
import com.binary.core.util.BinaryUtils;
import com.uinnova.project.base.diagram.comm.constant.CommonConst;
import com.uinnova.project.base.diagram.enums.LoginMethodEnum;
import com.uino.api.client.permission.IRoleApiSvc;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.base.SysRole;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.business.UserInfo;
import com.uino.bean.permission.query.CSysUser;
import com.uino.dao.permission.ESUserSvc;
import com.uino.util.sys.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;

/**
 * @author wang
 * @version 1.0
 * @description TODO
 * @date 2022-03-24-16:02
 */
@Slf4j
@Component
public class FilterUtil {

    @Value("${monet.login.loginMethod}")
    private  String loginMethod;

    @Value("${uino.user.rolename}")
    private  String roleName;

    @Autowired
    private  IRoleApiSvc roleApiSvc;

    @Autowired
    private  ESUserSvc esUserSvc;

    @Autowired
    private  IUserApiSvc userApiSvc;

    /**
     * @Author wang
     * @Description 根据数字空间响应信息获取用户信息
     * @Date 15:56 2021/8/31
     * @Param []
     **/
    public  SysUser getUserByWikiRes(String wikiRes) {
        SysUser currUser = new SysUser();
        JSONObject userJson = new JSONObject(wikiRes);
        //校验成功，处理信息
        String openid = userJson.getStr("openid");
        Long userId = userJson.getLong("user_id");
        if (userId == null) {
            return null;
        }
        UserInfo userInfo = new UserInfo();
        try {
            //2.查得到，说明用户信息已保存在本地
            CSysUser userQuery = new CSysUser();
            userQuery.setId(userId);
            List<UserInfo> userInfoByCdt = userApiSvc.getUserInfoByCdt(userQuery, true);
            if (!BinaryUtils.isEmpty(userInfoByCdt)) {
                userInfo = userInfoByCdt.get(0);
            }
        } catch (Exception e) {
            //3.查不到会报错，说明用户信息未保存在本地，需要保存
            log.info("用户未注册，自动注册");
        }
        if (BinaryUtils.isEmpty(userInfo.getId())) {
            String phone = userJson.getStr("phone");
            if (StringUtils.isEmpty(phone)) {
                phone = "13888888888";
            }

            String username = userJson.getStr("realname");
            userInfo.setId(userId);
            userInfo.setUserName(username);
            userInfo.setLoginCode(openid);
            userInfo.setMobileNo(phone);
            String email = userJson.getStr("email");
            userInfo.setEmailAdress(StringUtils.isEmpty(email) ? username + "@qq.com" : email);
            String avatar = userJson.getStr("avatar");
            userInfo.setIcon(StringUtils.isEmpty(avatar) ? CommonConst.DEFAULT_USER_ICON : avatar);
            userInfo.setDomainId(1L);
            userInfo.setLoginPasswd(randPwd(openid));
            userInfo.setCreator("WIKI_AUTO_CREATE");
            userInfo.setSuperUserFlag(0);
            userInfo.setStatus(1);
            userInfo.setLockFlag(0);
            userInfo.setTryTimes(0);
            userInfo.setLastLoginTime(System.currentTimeMillis());
            if (StringUtils.isEmpty(roleName)) {
                roleName = "admin";
            }
            boolean isGetRole = true;
            //如果是sso方式登录，需要判断是否为内部用户，如果是则分配角色，不是则不分配
            if (LoginMethodEnum.SSO.getValue().equals(loginMethod)) {
                Boolean isInternal = userJson.getBool("internal");
                if (isInternal == null) {
                    isGetRole = false;
                    log.info("无internal属性，不分配角色");
                } else {
                    if (!isInternal) {
                        isGetRole = true;
                    }
                }
            }
            if (!BinaryUtils.isEmpty(roleName) && isGetRole) {
                BoolQueryBuilder must = QueryBuilders.boolQuery().must(QueryBuilders.termsQuery("roleName.keyword", roleName));
                List<SysRole> sysRoles = roleApiSvc.getRolesByQuery(must);
                if (sysRoles != null && sysRoles.size() > 0) {
                    userInfo.setRoles(new HashSet<>(sysRoles));
                }
            }
            if (!BinaryUtils.isEmpty(userInfo)) {
                log.info("当前用户在系统不存在，新建用户：{}, 是否分配角色：{}", userInfo.getUserName(), isGetRole);
                userApiSvc.saveOrUpdate(userInfo);
            } else {
                return null;
            }
            currUser = BeanUtil.converBean(userInfo, SysUser.class);
        } else {
            String avatar = userJson.getStr("avatar");
            String newIcon = "";
            if (!StringUtils.isEmpty(avatar)) {
                if (!avatar.equals(userInfo.getIcon())) {
                    newIcon = avatar;
                }
            } else {
                if (StringUtils.isEmpty(userInfo.getIcon())) {
                    newIcon = CommonConst.DEFAULT_USER_ICON;
                }
            }
            //String newIcon = StringUtils.isEmpty(avatar) ? CommonConst.DEFAULT_USER_ICON : avatar;
            if (!StringUtils.isEmpty(newIcon)) {
                SysUser updateUser = new SysUser();
                updateUser.setId(userInfo.getId());
                updateUser.setIcon(newIcon);
                updateUser.setCreateTime(userInfo.getCreateTime());
                esUserSvc.saveOrUpdate(updateUser);
                userInfo.setIcon(newIcon);
            }
            currUser = BeanUtil.converBean(userInfo, SysUser.class);
        }
        return currUser.clearSensitive();
    }

    /**
     * @Author wang
     * @Description 生成随机密码
     * @Date 14:06 2021/9/6
     * @Param [loginCode]
     **/
    public String randPwd(String loginCode) {
        String a = "ab";
        String b = "cd";
        if (loginCode.length() > 4) {
            a = loginCode.substring(0, 2);
            b = loginCode.substring(2, 4);
        }
        return a + "T_w" + System.currentTimeMillis() % 100 + "er" + b + System.currentTimeMillis() % 1000;
    }
}
